<?php
/**
 * 微信小程序授权登陆
 */
namespace Api\Controller;

use Common\Model\UserModel;
use Common\Util\BaseData;
use Common\Util\WXBizDataCrypt;

class WeixinMpLoginController extends CommonController{

	public function userAuthSlogin(){
		$user_m = new UserModel();
		$content = $_POST;
		$code = $content["code"];
		$referee_id = intval($content["referee_id"]);//推荐人
		//获取新版本openid
		$app_setting = BaseData::getAppSetting();
		$param2['appid'] = $app_setting['wx_app_appid'];
		$param2['js_code'] = $code;
		$param2['grant_type'] = "authorization_code";
		$param2['secret'] = $app_setting['wx_app_appsecret'];
		$url = 'https://api.weixin.qq.com/sns/jscode2session?'.http_build_query($param2);
		$new_content = cyz_curl_get_contents($url);
		hx_write_app_log($new_content, 'weixinmin_login');
		$new_content = json_decode($new_content, true);

		if(!empty($new_content['errcode'])){
			echo json_encode(['success' => -1, 'errCode' => $new_content['errcode'], 'msg' => '获取用户信息出错']);
			exit();
		}
		$user_id = $this->wxUserAdd([
			'openId'     => $new_content['openid'],
			'referee_id' => $referee_id,
			'unionid'    => $new_content['unionid'] ? $new_content['unionid'] : '',
		]);
		if(empty($user_id)){
			echo json_encode(['success' => -1, 'errCode' => 0, 'msg' => '获取用户信息出错']);
			exit();
		}
		if(!$user_token = $user_m->updateUserLoginToken($user_id)){
			echo json_encode(['success' => -1, 'errCode' => 0, 'msg' => '登陆失败，请重试']);
			exit();
		}
		echo json_encode(['success' => 1, 'utoken' => $user_token, 'user_id' => $user_id]);
		exit();
	}

	/*code 换取 session_key*/
	public function getSession($code){
		$app_data = BaseData::getAppSetting();
		$s_data['appid'] = $app_data['wx_app_appid'];
		$s_data['secret'] = $app_data['wx_app_appsecret'];
		$s_data['js_code'] = $code;
		$s_data['grant_type'] = "authorization_code";
		$session_url = 'https://api.weixin.qq.com/sns/jscode2session?'.http_build_query($s_data);
		$content = cyz_curl_get_contents($session_url);
		$content = json_decode($content, true);
		$content['appid'] = $s_data['appid'];
		return $content;
	}

	/*插入小程序用户*/
	public function wxUserAdd($data){
		$user_m = new UserModel();
		$data['user_weixinmin_openid'] = $data['openId'] ? $data['openId'] : '';
		$data['user_weixin_unionid'] = $data['unionid'] ? $data['unionid'] : '';
		$referee_id = $data['referee_id'] ? $data['referee_id'] : 0;
		$referee_id = 0;
		unset($data['referee_id']);
		if($user_info = $user_m->where(['user_weixinmin_openid' => $data['user_weixinmin_openid']])->find()){
			$user_m->updateUserPath($user_info['id'], $referee_id);
			return $user_info['id'];
		}
		$data['referrer_user_id'] = 0;
		$data['user_path'] = '';
		$data['user_from'] = 'weixinmin';
		$data['user_type'] = 0;
		$data['user_openid'] = '';
		$data['user_weixin_openid'] = '';
		$data['user_alipay_openid'] = '';
		$data['user_nickname'] = '';
		$data['user_sex'] = 1;
		$data['user_country'] = '中国';
		$data['user_province'] = $data['province'] ? $data['province'] : '';
		$data['user_city'] = $data['city'] ? $data['city'] : '';
		$data['user_login_status'] = 1;
		$data['user_true_name'] = '';
		$data['user_true_phone'] = '';
		$data['user_phone_status'] = 0;
		$data['user_email'] = '';
		$data['user_token'] = '';
		$data['user_auth_sign'] = '';
		$data['user_auth_status'] = 0;
		$data['add_time'] = time();
		$data['update_time'] = time();
		if($insert_id = $user_m->add($data)){
			$user_m->updateUserPath($insert_id, $referee_id);
			return $insert_id;
		}else{
			return 0;
		}
	}

	/**
	 * 授权首页
	 */
	public function authIndex(){
		$this->checkUserUtoken($this->utoken);
		$this_app_config = BaseData::getAppSetting(true);
		$this->renderSuccess(['this_app_config' => $this_app_config]);
	}

	/**
	 * 同步更新用户信息
	 */
	public function updateUserInfo(){
		$this->checkUserUtoken($this->utoken);
		$t_user = M('user');
		$encryptedData = I("post.encryptedData");
		$iv = I("post.iv");
		$code = I("post.code");
		if($encryptedData && $iv && $code){
			$s_result = $this->getSession($code);
			if(empty($s_result['session_key']) || empty($s_result['openid'])){
				$this->renderError('授权失败，请返回重试22！');
			}
			$WxData = new WXBizDataCrypt($this->this_app_config['wx_app_appid'], $s_result['session_key']);
			$user_data = "";
			$errCode = $WxData->decryptData($encryptedData, $iv, $user_data);
			if($errCode == 0){
				$user_data = json_decode($user_data, true);
				$nickName = $user_data['nickName'];
				$res = $t_user->where(['user_weixinmin_openid' => $s_result['openid']])->save([
					'user_nickname'    => $nickName,
					'user_sex'         => $user_data['gender'],
					'user_language'    => $user_data['language'],
					'user_country'     => $user_data['country'],
					'user_province'    => $user_data['province'],
					'user_city'        => $user_data['city'],
					'user_headimg'     => $user_data['avatarUrl'],
					'user_auth_status' => '1',
					'update_time'      => time(),
				]);
				if($res){
					$this->renderSuccess([], "授权成功");
				}else{
					$this->renderError('授权失败，请返回重试33！');
				}
			}else{
				$this->renderError('授权失败，请返回重试44！');
			}
		}else{
			$this->renderError('请求参数缺失！');
		}
	}

	//获取用户手机号码
	public function updateUserPhone(){
		$this->checkUserUtoken($this->utoken);
		$user_m = new UserModel();
		$encryptedData = I("post.encryptedData");
		$iv = I("post.iv");
		$code = I("post.code");
		if($encryptedData && $iv && $code){
			$s_result = $this->getSession($code);
			if(empty($s_result['session_key']) || empty($s_result['openid'])){
				$this->renderError('授权失败，请返回重试！');
			}
			$WxData = new WXBizDataCrypt($this->this_app_config['wx_app_appid'], $s_result['session_key']);
			$user_data = "";
			$errCode = $WxData->decryptData($encryptedData, $iv, $user_data);
			if($errCode == 0){
				$user_data = json_decode($user_data, true);
				$user_true_phone = $user_data['purePhoneNumber'];
				if($user_m->where(['user_true_phone' => $user_true_phone])->find()){
					$this->renderError('该手机号已注册！');
				}
				$res = $user_m->where(['user_weixinmin_openid' => $s_result['openid']])->save([
					'user_true_phone'   => $user_true_phone,
					'user_phone_status' => 1,
					'user_auth_status'  => 2,
					'update_time'       => time(),
				]);
				if($res){
					//新用户注册业务处理
					$user_m->userRegAction($this->this_user_id);
					$this->renderSuccess([], "授权成功");
				}else{
					$this->renderError('授权失败，请重试！');
				}
			}else{
				$this->renderError('授权失败，请重试！');
			}
		}else{
			$this->renderError('请求参数缺失！');
		}
	}
}
